package com.gzdh.device.comm.util;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.DialectModel;
import com.baomidou.mybatisplus.extension.plugins.pagination.dialects.IDialect;

public class MycatSqlserverDialect implements IDialect {
 
 
    private static String getOrderByPart(String sql) {
        //将字符串中的所有大写字母转换为小写字母
        String loweredString = sql.toLowerCase();
        int orderByIndex = loweredString.indexOf("order by");
        if (orderByIndex != -1) {
            return sql.substring(orderByIndex);
        } else {
            return StringPool.EMPTY;
        }
    }
 
    @Override
    public DialectModel buildPaginationSql(String originalSql, long offset, long limit) {
        StringBuilder pagingBuilder = new StringBuilder();
        String orderby = getOrderByPart(originalSql);
        String distinctStr = StringPool.EMPTY;
 
 
        String loweredString = originalSql.toLowerCase();
        String sqlPartString = originalSql;
        if (loweredString.trim().startsWith("select")) {
            int index = 6;
            if (loweredString.startsWith("select distinct")) {
                distinctStr = "DISTINCT ";
                index = 15;
            }
            sqlPartString = sqlPartString.substring(index);
        }
        //识别mycat 的注解
        else if(loweredString.trim().startsWith("/* !mycat:")){
            int index=6;
            if (loweredString.contains("select distinct")) {
                distinctStr = "DISTINCT ";
                 index = 15;
            }
            //截取mycat 注解和 sql 语句
            int i = sqlPartString.indexOf("/", 1);
            String mycatSql = sqlPartString.substring(0, i+1);
            String sql = sqlPartString.substring(i + 1);
            int s = sql.indexOf("s");
            sql = sql.substring(s+index);
            StringBuilder mycatBuilder = new StringBuilder();
            mycatBuilder.append(mycatSql);
            StringBuilder sqlBuilder = new StringBuilder();
            sqlBuilder.append(sql);
            if (StringUtils.isEmpty(orderby)) {
                orderby = "ORDER BY CURRENT_TIMESTAMP";
            }
            long firstParam = offset + 1;
            long secondParam = offset + limit;
            //把mycat注解放到sql 语句前面 指定数据库进行查询
            String MycatSql = mycatBuilder+"WITH selectTemp AS (SELECT " + distinctStr + "TOP 100 PERCENT " +
                    " ROW_NUMBER() OVER (" + orderby + ") as __row_number__, " + sqlBuilder +
                    ") SELECT * FROM selectTemp WHERE __row_number__ BETWEEN " +
                    //FIX#299：原因：mysql中limit 10(offset,size) 是从第10开始（不包含10）,；而这里用的BETWEEN是两边都包含，所以改为offset+1
                    firstParam + " AND " + secondParam + " ORDER BY __row_number__";
            return new DialectModel(MycatSql, firstParam, secondParam);
 
        }
        pagingBuilder.append(sqlPartString);
 
        // if no ORDER BY is specified use fake ORDER BY field to avoid errors
        if (StringUtils.isEmpty(orderby)) {
            orderby = "ORDER BY CURRENT_TIMESTAMP";
        }
        long firstParam = offset + 1;
        long secondParam = offset + limit;
        String sql = "WITH selectTemp AS (SELECT " + distinctStr + "TOP 100 PERCENT " +
                " ROW_NUMBER() OVER (" + orderby + ") as __row_number__, " + pagingBuilder +
                ") SELECT * FROM selectTemp WHERE __row_number__ BETWEEN " +
                //FIX#299：原因：mysql中limit 10(offset,size) 是从第10开始（不包含10）,；而这里用的BETWEEN是两边都包含，所以改为offset+1
                firstParam + " AND " + secondParam + " ORDER BY __row_number__";
        return new DialectModel(sql, firstParam, secondParam);
    }
 
}